<template>
  <div style="">
    <el-form ref="temp" :rules="rules" :model="temp" label-position="left" label-width="110px" style="margin-left:70px;margin-right:70px;">
      <el-form-item label="头像" prop="Avatar">
        <el-upload
          class="avatar-uploader"
          action="#"
          :http-request="upload"
          :show-file-list="false"
          accept="image/*"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="temp.Avatar" :src="temp.Avatar" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon" />
        </el-upload>
      </el-form-item>
      <el-form-item label="用户名" prop="UserName">
        <el-input v-model.trim="temp.UserName" placeholder="请输入用户名" clearable :disabled="operationType === 'edit'" @blur="checkUserName" />
      </el-form-item>
      <el-form-item v-if="operationType === 'add'" label="密码" prop="PassWord">
        <el-input v-model.trim="temp.PassWord" type="password" maxlength="16" minlength="6" placeholder="请输入密码" clearable autocomplete="new-password" />
      </el-form-item>
      <el-form-item label="性别" prop="Gender">
        <el-radio v-model="temp.Gender" :label="0">保密</el-radio>
        <el-radio v-model="temp.Gender" :label="1">男性</el-radio>
        <el-radio v-model="temp.Gender" :label="2">女性</el-radio>
      </el-form-item>
      <el-form-item label="电话" prop="Mobile">
        <el-input v-model.trim="temp.Mobile" placeholder="请输入电话" clearable />
      </el-form-item>
      <el-form-item label="公司" prop="CompanyName">
        <el-select v-model="temp.CompanyName" value-key="CompanyId" placeholder="请选择公司" @change="getCompanyOption">
          <el-option v-for="(item) in companyList" :key="item.CompanyId" :label="item.CompanyName" :value="item.CompanyName" />
        </el-select>
      </el-form-item>
      <el-form-item label="部门" prop="DepartmentName">
        <el-select v-model="temp.DepartmentName" value-key="DepartmentId" placeholder="请选择部门" @change="getDepartmentOption">
          <el-option v-for="(item) in departmentList" :key="item.DepartmentId" :label="item.DepartmentName" :value="item.DepartmentName" />
        </el-select>
      </el-form-item>
      <el-form-item label="地区" prop="Location">
        <el-input v-model.trim="temp.Location" placeholder="请输入地区" clearable />
      </el-form-item>
      <el-form-item label="身份证号码" prop="IDCard">
        <el-input v-model.trim="temp.IDCard" placeholder="请输入身份证号码" clearable />
      </el-form-item>
      <el-form-item label="生日" prop="BirthDay">
        <el-date-picker
          v-model="temp.BirthDay"
          type="date"
          placeholder="选择日期"
        />
      </el-form-item>
      <el-form-item label="添加好友方式" prop="AllowType">
        <el-radio v-model="temp.AllowType" :label="0">允许任何人添加自己为好友</el-radio>
        <el-radio v-model="temp.AllowType" :label="1">需要经过自己确认对方才能添加自己为好友</el-radio>
        <el-radio v-model="temp.AllowType" :label="2">不允许任何人添加自己为好友</el-radio>
      </el-form-item>
      <el-form-item label="个性签名" prop="SelfSignature">
        <el-input
          v-model.trim="temp.SelfSignature"
          placeholder="请输入个性签名"
          type="textarea"
          rows="5"
        />
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer" style="text-align: center;">
      <el-button @click="cancel">
        取消
      </el-button>
      <el-button type="primary" :loading="loading" @click="createData">
        确认
      </el-button>
    </div>
  </div>
</template>

<script>
import { validateUsername, validatePassword, validateNickName, validateCompany, validateDepartment } from '@/utils/validator'

import { GetDepartmentList } from '@/api/Department'
import { GetCompanyList } from '@/api/Company'
import { CheckUserName, GetUserById } from '@/api/User'
import { TipsBox } from '@/utils/feedback'
import { UploadFile } from '@/api/File'
import dayjs from 'dayjs'

export default {
  name: 'DataForm',
  props: {
    operationType: { type: String, default: '' },
    loading: { type: Boolean, default: false },
    editData: { type: Object, default: null }
  },
  data() {
    return {
      temp: {
        UserId: '',
        UserName: '',
        PassWord: '',
        Gender: 0, // 默认
        Mobile: '',
        CompanyId: '', // 默认
        CompanyName: '',
        CompanyNickName: '',
        DepartmentId: '',
        DepartmentName: '',
        PositionId: '',
        PositionName: '',
        CRMUserID: 0,
        IDCard: '',
        BirthDay: '', // 必填
        Location: '',
        AllowType: 0,
        SelfSignature: '',
        Avatar: '',
        Enabled: 0,
        MacAdd: ''
      },
      rules: {
        UserName: [{ required: true, trigger: 'blur', validator: validateUsername }],
        NickName: [{ required: true, trigger: 'blur', validator: validateNickName }],
        PassWord: [{ required: true, trigger: 'blur', validator: validatePassword }],
        CompanyName: [{ required: true, trigger: 'blur', validator: validateCompany }],
        DepartmentName: [{ required: true, trigger: 'blur', validator: validateDepartment }]
      },
      companyList: [],
      departmentList: [],
      canUpdate: false
    }
  },
  watch: {
    // 监听对象
    operationType: {
      handler(newVal) {
        this.operationType = newVal
        this.getFormType() // 好像没走这个方法
      },
      deep: true
    }
  },
  mounted() {
    this.getFormType()
    this.getCompanyList()
    this.getDepartmentList()
  },
  methods: {
    cancel() {
      this.$emit('dialogFormVisibleEmit', false)
    },
    getFormType() {
      if (this.operationType === 'edit') {
        GetUserById(`userId=${this.editData.UserId}`).then(res => {
          if (res.statusCode === 200) {
            //  取交集（以编辑数据为准）
            Object.keys(this.temp).map(key => res.data[key] && (this.temp[key] = res.data[key]))
            this.temp.BirthDay = dayjs(this.temp.BirthDay).format('YYYY-MM-DD')
          }
        })

        //  编辑无需验证 UserName
        this.canUpdate = true
      } else if (this.operationType === 'add') {
        // 清空表单
        this.$refs['temp'].resetFields()
        this.temp = { ...this.temp, ...{
          CreateUserId: this.$store.getters.userId,
          CreateBy: this.$store.getters.userName,
          CreateOn: dayjs().format('YYYY-MM-DD HH:mm:ss.SSS')
        }}
      }
    },
    //
    createData() {
      // return
      this.$refs['temp'].validate((valid) => {
        if (valid) {
          if (this.temp.BirthDay) {
            this.temp.BirthDay = dayjs(this.temp.BirthDay).format('YYYYMMDD')
          }

          this.canUpdate && this.$emit('createDataEmit', this.temp)
        }
      })
    },
    getCompanyOption(val) {
      this.temp.CompanyName = val
      const company = this.companyList.find(item => item.CompanyName === val)
      this.temp.CompanyId = company.CompanyId
    },
    getDepartmentOption(val) {
      this.temp.DepartmentName = val
      const department = this.departmentList.find(item => item.DepartmentName === val)
      this.temp.DepartmentId = department.DepartmentId
    },
    //  上传成功
    handleAvatarSuccess(response, file, fileList) {
      this.temp.Avatar = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type.includes('image')
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('只能上传图片!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    upload(file) {
      const formData = new FormData()
      formData.append('file', file.file)
      UploadFile(formData).then(res => {
        let type = 'error'
        if (res.statusCode === 200) {
          type = 'success'
          this.temp.Avatar = res.data
        }

        TipsBox(type, res.message)
      })
    },
    //  公司列表
    getCompanyList() {
      GetCompanyList().then((res) => {
        if (res.statusCode === 200) {
          this.companyList = res.data
        }
      })
    },
    //  部门列表
    getDepartmentList() {
      GetDepartmentList().then((res) => {
        if (res.statusCode === 200) {
          this.departmentList = res.data
        }
      })
    },
    // 检查用户名是否存在
    checkUserName(e) {
      if (e.target.value) {
        CheckUserName(`userName=${e.target.value}`).then((res) => {
          if (res.statusCode === 200) {
            this.canUpdate = true
          } else {
            this.canUpdate = false
            TipsBox('error', res.message)
          }
        })
      }
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9 !important;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 70px;
  height: 70px;
  line-height: 70px;
  text-align: center;
}
.avatar {
  width: 70px;
  height: 70px;
  display: block;
}
</style>
